{extends file="base.html"}
{block name=function}

{function name=form_elem_text mdl=null field=null col=null}
	{if $sub_elem=='title'}
    {$form->text("$mdl.$field",['class' => 'layui-input text-input form_item form_item_title', 'placeholder' => $col.placeholder|default:''])}
    {else}
    {$form->text("$mdl.$field",['class' => 'layui-input text-input form_item', 'placeholder' => $col.placeholder|default:''])}
    {/if}
    
    {if isset($col.quick)}
        {if dict($mdl,$field)}
        {$options=[]}
        {foreach dict($mdl,$field) as $v}
        {$options.$v=$v}
        {/foreach}
        {$form->select("$mdl.$field",$options,['class'=>'form_item quick_select_item','name'=>false,'lay-search'=>'','lay-filter'=>'quick_select_item','empty'=>"≡快捷选项≡"])}
        {else}
            <a href="{url('Dictionary/create',['model'=>$mdl,'field'=>$field,'title'=>$mdls.$mdl->cname|cat:'.'|cat:$col.name])}" class="layui-btn new_tab">添加选项</a>
        {/if}
    {/if}
       
{/function}

{function name=form_elem_number mdl=null field=null col=null}
    {$form->number("$mdl.$field",['class' => 'layui-input text-input form_item' ,'placeholder' => $col.placeholder|default:''])}
{/function}

{function name=form_elem_tag mdl=null field=null col=null}
    <div class="form_tag_container" data-length="{$col.tag_length|default:0}">{strip}
        {$form->hidden("$mdl.$field",['class' => 'layui-input text-input form_item'])}
        {$value=$cthis->Form->data.$mdl.$field}
        {if $value}
        {$value_array = explode(',', $value)}
        {foreach $value_array as $tag}        
        <a class="tag_each" data-value="{$tag}">{$tag}<i class="fa fa-close"></i></a>
        {/foreach}
        {/if}
        <input  type="text" class="tag_write" autocomplete="off"/>
    {/strip}</div>
{/function}

{function name=form_elem_color mdl=null field=null col=null}
    {$local.val=$cthis->Form->data.$mdl.$field}
    <div class="colorBox">
        {$form->hidden("$mdl.$field",['class' => 'color'])}
        <div class="color color_{$field}" style="{if $local.val}background-color:{$local.val};{/if}"></div>
    </div>
    <script type="text/javascript">
    $('.color_{$field}').ColorPicker({
        onShow : function(colpkr){
            $(colpkr).stop(true,true).fadeIn(500);
            var color  = $('.color_{$field}').parent().find('input').val();
            if(color)  $('.color_{$field}').ColorPickerSetColor(color);
            return false;
        },
        onHide: function (colpkr) {
    		$(colpkr).stop(true,true).fadeOut(500);
    		return false;
    	},
        onChange : function(hsb, hex, rgb){
            $('.color_{$field}').css('background-color', '#' + hex).parent().find('input').val('#' + hex) ;
        }
    });
    </script>    
{/function}

{function name=form_elem_password mdl=null field=null col=null}	
	{$form->password("$mdl.$field",['class' => 'layui-input text-input form_item', 'empty'=>true, 'value'=>'', 'placeholder' => $col.placeholder|default:''])}
{/function}

{function name=form_elem_select mdl=null field=null col=null}
	{$form->select("$mdl.$field",$col.options,['class'=>'form_item','multiple'=>$col.multiple,'lay-search'=>'','lay-filter'=>$field,'empty'=>"≡请选择{$col.name}≡"])}
{/function}

{function name=form_elem_checker mdl=null field=null col=null}
	{$form->checkbox("$mdl.$field",[],['class' => "form_item" ,'lay-skin'=>'switch','lay-filter'=>$field,'lay-text'=>"Y|N"])}
{/function}

{function name=form_elem_checkbox mdl=null field=null col=null}
	{$form->checkbox("$mdl.$field",$col.options,['div' => false,'lay-skin'=>'primary','lay-filter'=>$field,'class'=>'form_item'])}
{/function}

{function name=form_elem_hidden mdl=null field=null col=null}
	{$form->hidden("$mdl.$field",['class'=>'form_item'])}
{/function}

{function name=form_elem_radio mdl=null field=null col=null}
	{$form->radio("$mdl.$field",$col.options,['class'=>'form_item','label'=>false,'lay-filter'=>$field,'title'=>true,'notext'=>true])}
{/function}

{function name=form_elem_textarea mdl=null field=null col=null}	
	{$form->textarea("$mdl.$field",['class' => 'layui-textarea  form_item' ,'placeholder' => $col.placeholder|default:''])}
{/function}

{function name=form_elem_date mdl=null field=null col=null}
    {$form->text("$mdl.$field",['class' => 'layui-input text-input form_item datepicker', 'placeholder' => $col.placeholder|default:'', 'data-lang' => $col.options.lang|default:'cn', 'data-trigger' => $col.options.trigger|default:'focus', 'data-type' => $col.options.type|default:'date', 'data-range' => $col.options.range|default:'', 'data-min' => $col.options.min|default:'', 'data-max' => $col.options.max|default:'', 'data-theme' => $col.options.theme|default:'default', 'data-calendar' => $col.options.calendar|default:''])}
{/function}

{function name=form_elem_datetime mdl=null field=null col=null}
    <div class="form-error-tip">“datetime”已废弃，请将“elem”设置为“date”，字段“options”中“type” => “datetime”</div>
{/function}

{function name=form_elem_month mdl=null field=null col=null} 
    <div class="form-error-tip">“month”已废弃，请将“elem”设置为“date”，字段“options”中“type” => “month”</div>
{/function}

{function name=form_elem_year mdl=null field=null col=null} 
    <div class="form-error-tip">“year”已废弃，请将“elem”设置为“date”，字段“options”中“type” => “year”</div>
{/function}

{function name=form_elem_time mdl=null field=null col=null} 
    <div class="form-error-tip">“time”类型已废弃，请将“elem”设置为“date”，字段“options”中“type” => “time”</div>
{/function}

{function name=form_elem_editor mdl=null field=null col=null}
    {$form->textarea("$mdl.$field",['class' => 'form_item editor editor_'|cat:$field])}          
{/function}

{function name=form_elem_array mdl=null field=null col=null}
    {$form->hidden("$mdl.$field",['class'=>'form_item'])}
    <div class="array">
    </div>
    <a class="javascript edit_array layui-btn" rel="edit_array" >编辑</a>
{/function}

{function name=form_elem_keyvalue mdl=null field=null col=null}
    {$form->hidden("$mdl.$field",['class'=>'form_item'])}
    <div class="array"></div>
    <a class="javascript edit_array  layui-btn  keyvalue" rel="edit_array" >编辑</a>
{/function}

{function name=form_elem_image mdl=null field=null col=null}
    {$thumb_field=$col.image.thumb.field|default:$field}
    <div class="clearfix">
        <a href="javascript:void(0);" class="upload_elem_box">
            {$form->file("$mdl.upload.$field",['class'=>'form_upload','accept'=>'image/png,image/gif,image/jpeg'])}
            <i class="fa fa-cloud-upload fa-lg"></i>图片上传
        </a><span class="upload_elem_info"></span>
    </div> 
    {if $form->data[$mdl][$field]}
    {$show_src = $form->data[$mdl][$field]}
    <div class="clearfix form_elem_info">
        {$form->hidden("$mdl.$field",['value'=>$form->data[$mdl][$field],'class'=>'form_item form_file_hidden'])}
        {if isset($col.image.thumb)}
            {$thumb_field=$col.image.thumb.field|default:'thumb'}
            {$show_src=$form->data[$mdl][$thumb_field]}
            {$form->hidden("$mdl.$thumb_field",['value'=>$form->data[$mdl][$thumb_field],'class'=>'form_item form_file_hidden'])}
        {/if}
        <a href="javascript:void(0);" class="img_show">
            <img  src="{call furl url=$show_src}" width="100" alt="缩略图"/>
            <span  class="btn upload_remove_btn eft tooltip" data-tip-text="删除文件"><i class="fa fa-trash fa-lg"></i></span>
        </a>
    </div>
    {/if}    	
{/function}

{function name=form_elem_file mdl=null field=null col=null}
    <div class="clearfix">
        <a href="javascript:void(0);" class="upload_elem_box">
            {$form->file("$mdl.upload.$field",['class'=>'form_upload'])}
            <i class="fa fa-cloud-upload fa-lg"></i>文件上传
        </a><span class="upload_elem_info"></span>
    </div> 
    {if $form->data[$mdl][$field]} 
    {$src=$form->data[$mdl][$field]} 
    <div class="clearfix form_elem_info">
        {$form->hidden("$mdl.$field",['value'=>$src,'class'=>'form_item form_file_hidden'])}
        <a href="{call furl url=$src}" target="_blank" class="file_show">
            <i class="fa  fa-cloud-download fa-lg"></i>文件下载
            <span  class="btn upload_remove_btn eft tooltip" data-tip-text="删除文件"><i class="fa fa-trash fa-lg"></i></span>
        </a>
    </div>
    {/if}    	
{/function}

{function name=form_elem_format mdl=null field=null col=null}
	{$local.val=$cthis->Form->data.$mdl.$field}
    {$form->hidden("$mdl.$field",['class'=>'form_item'])}
	{if $col.options}{$local.val=$col.options[$local.val]}{/if}
	{if !$col.format}{$col.format='{'|cat:$field|cat:'}'}{/if}
	<span class="display" title="{$local.val}">
	{if $col.length}{$local.val=$local.val|cn_truncate:$col.length}{/if}
    {$local.temp=$cthis->Form->data}
    {$local.temp.$field=$local.val}
	{string_insert($col.format|default:$local.val,$local.temp)}
	</span>
{/function}

{function name=form_elem_nest_select_options data=[] level=0}
    {foreach $data as $self_id=>$children}{strip}
    {if $children@first}
    <div class="menu_option menu_option_level_{$level} menu_option_parent_{$fulldata.list[$self_id].parent_id} {if !in_array($self_id,$family)&&!in_array({$fulldata.list[$self_id].parent_id},$family)&&$level>0}hidden{/if}">
    {/if}   
        {*$data_family = substr(substr(menu($self_id,'family'),1),0,-1)}
        {if !$data_family}{getClosestFamily('AdminMenu',$self_id,$data_family)}{$data_family=implode($data_family,',')}{/if*}
        <a href="javascript:void(0);" class="each_nav each_nav_{$self_id} {if in_array($self_id,$family)}same{/if}"  data-id="{$self_id}"  {*data-family="{$data_family}"*} data-parent="{$fulldata.list[$self_id].parent_id}">{$fulldata.list[$self_id].title}</a>
    {if $children@last} 
    </div>
    {/if}
    {/strip}{/foreach}
    {foreach $data as $self_id=>$children}
    {if $children}
    {call form_elem_nest_select_options data=$children level=$level+1}
    {/if}
    {/foreach}
{/function}

{function name=form_elem_icon mdl=null field=null col=null}
    <div class="icon_select">
        {$form->text("$mdl.$field",['class' => 'layui-input text-input form_item'])}        
        <a href="javascript:void(0);" class="icon_select_action layui-btn layui-btn-primary">搜索图标</a>
        <div class="icon_select_options sizing">
            <div class="loading">
                图标加载中...　<a href="http://code.zoomla.cn/boot/font.html" target="_blank">访问图标原站点</a>
            </div>
        </div>
    </div>
{/function}

{function name=form_elem_nest_select mdl=null field=null col=null}
    {$parent_id=$form->data.$mdl.$field|default:0}
    {getClosestFamily($sub_elem,$parent_id,$family)}
    {$fulldata=read_file_cache($sub_elem)}
    
     <div class="menu_select">
        {$form->hidden("$mdl.$field",['class'=>'form_item','value'=>$parent_id])}
        <div class="menu_select_show">
            {foreach $family as $famly_id}
            {$fulldata.list[$famly_id].title|default:'未选择'}{if !$famly_id@last}<i>&gt;</i>{/if}
            {/foreach}
        </div>
        <a href="javascript:void(0);" class="menu_select_action layui-btn  layui-btn-normal">重新选取</a>   
        <div class="menu_select_options sizing">
            {call form_elem_nest_select_options data=$fulldata.threaded  level=0}
        </div> 
    </div>   
{/function}

{function name=form_elem_multi_select_parent mdl=null field=null col=null}
    {$parent_id = $form->data.$mdl.$field|default:0}
    <div class="multi_select multi_select_{$field} clearfix"></div>
    {if $sub_elem !== 'ajax'}
        {$select_name = 'multi_select_'|cat:parse_name($sub_elem)}
        {$cache = read_file_cache($select_name)}
        {if !empty($cache)}    
        {$min=$cache.data.top_id}
        {$cache.data.top_id=$cache.list[$min].parent_id}
        {$cache.options[$cache.data.top_id] = [$min]}
        {$cache.list[$cache.data.top_id]=['id' => $cache.data.top_id, 'title' => '根节点','parent_id' => -1]}
        {$cache = json_encode($cache)}
        {call name=form_elem_hidden mdl=$mdl field=$field col=$col}        
        <script> 
            new multi_select('{$field}', {$cache}, {$parent_id}, '{$mdl}', [])
        </script>
        {/if}
    {else}
        {$default_value=[]}
        {if $parent_id}{$default_value = $cthis->mdl->getFamily($field, $parent_id)}{/if}
        {$default_value = array_merge([$col.top_id|default:0], $default_value)}
        {call name=form_elem_hidden mdl=$mdl field=$field col=$col}
        <script>  
        new multi_select('{$field}', {json_encode(['options' => 'ajax', 'data'=>['top_id'=>$col.top_id|default:0]])}, {json_encode($default_value)}, '{$mdl}', {json_encode($col.multi_field|default:[])})
        </script>
    {/if}
{/function}

{function name=form_elem_multi_select mdl=null field=null col=null}
    {$parent_id = $form->data.$mdl.$field|default:0}
    {if !isset($col.multi_field)}{call name=form_elem_hidden mdl=$mdl field=$field col=$col}{/if}
    <div class="multi_select multi_select_{$field} clearfix"></div>    
    {if $sub_elem !== 'ajax'}
        {$select_name = 'multi_select_'|cat:parse_name($sub_elem)}
        {$cache = read_file_cache($select_name)}
        {if !empty($cache)}  
            
            {if !isset($col.multi_field)}  
                {$cache = json_encode($cache)}              
                <script> 
                new multi_select('{$field}', {$cache}, {$parent_id}, '{$mdl}', {json_encode($col.multi_field|default:[])})
                </script>
            {else}
                {$default_value=[]}
                {foreach $col.multi_field as $mfield=>$mtitle}
                    {if $form->data.$mdl.$mfield}
                        {$default_value[]=$form->data.$mdl.$mfield}
                    {/if}
                {/foreach}
                {$top_id=$cache.data.top_id}
                {$cache = json_encode($cache)}
                <script>  
                new multi_select('{$field}', {$cache}, {json_encode(array_merge([$top_id], $default_value))}, '{$mdl}', {json_encode($col.multi_field|default:[])})
                </script>
            {/if} 
        {else}
             <div class="form-error-tip">缺少缓存数据</div>
        {/if}           
    {else}
        {if !isset($col.multi_field)}
            {$default_value=[]}
            {if $parent_id}{$default_value = $cthis->mdl->getFamily($field, $parent_id)}{/if}
            <script>  
            new multi_select('{$field}', {json_encode(['options' => 'ajax', 'data'=>['top_id'=>$col.top_id|default:1]])}, {json_encode($default_value)}, '{$mdl}', {json_encode($col.multi_field|default:[])})
            </script>
        {else}
            {$default_value=[]}
            {foreach $col.multi_field as $mfield=>$mtitle}
                {if $form->data.$mdl.$mfield}
                    {$default_value[]=$form->data.$mdl.$mfield}
                {/if}
            {/foreach}
            <script>  
            new multi_select('{$field}', {json_encode(['options' => 'ajax', 'data'=>['top_id'=>$col.top_id|default:1]])},{json_encode(array_merge([$col.top_id|default:1], $default_value))}, '{$mdl}', {json_encode($col.multi_field|default:[])})
            </script>
        {/if}  
    {/if}
{/function}

{function name=form_elem_assoc_select mdl=null field=null col=null}
{call name=form_elem_hidden mdl=$mdl field=$field col=$col}
{if $col.foreign}
{$value=$form->data.$mdl.$field}
<span class="assoc_select_value">{if $value}{$value}=>{$assoc_value.$field|default:$value}{else}无选值{/if}</span>
<a href="{url('assoc_select', ['assoc' => $col.foreign])}" rel="assoc_select_load" class="javascript layui-btn">选择</a>
{else}
<div class="form-error-tip">表单缺少“foreign”属性</div>
{/if}
{/function}


{$smarty.block.child}
{/block}

{block name=base}
<div class="box_form">
    {$form_group_keys=[]}
    {if isset($cthis->mdl->formGroup)}
    {$form_group_keys = array_keys($cthis->mdl->formGroup)}
    <div class="form_selector tooltip" data-tip-text="快捷切换：ALT+Q" data-tip-type="4">
        <ul class="list">
            {foreach $cthis->mdl->formGroup as $key=>$name}
            <li class="basic_selector {if $key =='basic'}current{/if}" data-group-key="{$key}" >{$name}</li>
            {/foreach}
        </ul>
    </div>
    {/if}
    
    <div class="box_content">
        {if $warning}
        <blockquote class="site-text layui-elem-quote form_warning">
            <a href="javascript:void(0);" class="close" onclick="$(this).parent().slideUp(500);"><i class="fa fa-close"></i></a>
            {$warning}
        </blockquote>        
        {/if}
        
        {$form->create(['type'=>'file','class'=>'MainForm layui-form layui-form-pane','novalidate'=>true])}
        {block name=form_content}
            {foreach $cthis->mdl->form as $field=>$col}
                {if $col.elem===0}
    				{continue}
    			{elseif $col.elem==='hidden'}
    				{call name=form_elem_hidden mdl=$mdl field=$field col=$col}
    				{continue}
    			{/if}
                
                {$local.elem = PluginSplit($col.elem)}
                {if $local.elem[0]}
                	{$elem=$local.elem[0]}
                    {$sub_elem=$local.elem[1]}
                {else}
                	{$elem=$local.elem[1]}
                    {$sub_elem=NULL}
                {/if}     
                {if method_exists($mdls.$mdl,'getError')}    
                {$local.error=$mdls.$mdl->getError()|default:$mdl_error|default:[]}
                {else}
                {$local.error=$mdl_error|default:[]}
                {/if}
                {$local.error.fields=array_keys($local.error)}
                {$elem_group = $col.elem_group|default:'basic'}
                <div class="layui-form-item form-item-row form-item-field-{$field} form-item-{$elem} form-item-group-{$elem_group} {if $form_group_keys && $elem_group != 'basic' && !in_array($field,$local.error.fields)}hidden{/if} {if isset($col.quick)}quick_row{/if}">
                    <label class="layui-form-label">{$col.name}：</label>
                    <div class="layui-input-inline">                    
                    {$local.func='form_elem_'|cat:$elem}
                    {call name=$local.func mdl=$mdl field=$field col=$col sub_elem=$sub_elem class=" form_item_input_{$field}"}
                    </div>
                    {if $col.info}
                    <div class="layui-item-info tooltip" data-tip-text="{htmlspecialchars($col.info)}" data-tip-bg="#FF5722" data-tip-type="3" ><i class="fa fa-bell fa-lg"></i></div>
                    {/if}
                    
                    {if isset($local.error.$field)}<div class="layui-input-error"><i class="fa fa-times"></i>{$local.error.$field|default:'该字段有误'}</div>{/if}
                    {*if $col.info}
                    <div class="layui-item-info"><i class="fa fa-exclamation"></i>{$col.info}</div>
                    {/if*}
                </div>
            {/foreach}
                <div class="layui-form-item form-item-btns">
                    <div class="layui-input-inline">
                      <button class="layui-btn layui-btn-normal" lay-submit >立即提交</button>
                      <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                    </div>
                </div>
        {/block}
        {$form->end()}
    </div>
</div>


{/block}

{block name=script}
<script type="text/javascript">
var laydate,form;
layui.use(['form','element','laydate'], function(){
    form = layui.form;
    laydate = layui.laydate;
    
    $('.datepicker').each(function(){
        var range = false;
        if ($(this).data('range')) {
            if ($(this).data('range') == '1') {
                range = '~'
            } else {
                range = $(this).data('range');
            }
        }        
        laydate.render({ 
          elem: this
          ,type: $(this).data('type') ? $(this).data('type') : 'date'
          ,trigger: $(this).data('trigger') ? $(this).data('trigger') : 'focus'
          ,range : range
          ,min : $(this).data('min') ? $(this).data('min') : {}
          ,max : $(this).data('max') ? $(this).data('max') : {}
          ,lang : $(this).data('lang') ? $(this).data('lang') : 'cn'
          ,theme : $(this).data('theme') ? $(this).data('theme') : 'default'
          ,calendar : !$(this).data('calendar') ? false : true
        });
    })
    
    
    form.on('select(quick_select_item)', function(data){
        $(data.elem).closest('.layui-input-inline').find('.form_item').val(data.value);
    })
    
    //字段响应处理
    {if $cthis->mdl->fieldRespond}
    {foreach $cthis->mdl->fieldRespond as $field=>$respond}
        $('.form-item-field-{$field}').find('.form_item[name="data[{$mdl}][{$field}]"]').change(function(){
            {if $respond.RespondField}
                {foreach $respond.RespondField as $hideField}
                $('.form-item-field-{$hideField}').addClass('r-hidden') ;
                {/foreach}
            {/if}
            {if in_array($cthis->mdl->form[$field]['elem'],array('checkbox','radio','checker')) }
            var changeVal  =  $(this).closest('.layui-input-inline').find(':checked').val();
            {else}
            var changeVal  =  $(this).val();
            {/if}
            {foreach $respond as $value=>$showFields}
            {if $value == 'RespondField'}{continue}{/if}
            if(changeVal == '{$value}'){
                {foreach $showFields as $showField}
                $('.form-item-field-{$showField}').removeClass('r-hidden') ;
                {/foreach}
            }
            {/foreach}
        }).trigger('change');   
        
        {if $cthis->mdl->form[$field]['elem'] =='select'}
        form.on('select({$field})', function(data){
            {if $respond.RespondField}
                {foreach $respond.RespondField as $hideField}
                $('.form-item-field-{$hideField}').addClass('r-hidden') ;
                {/foreach}
            {/if}
            var changeVal  =  data.value;
            {foreach $respond as $value=>$showFields}
            {if $value == 'RespondField'}{continue}{/if}
            if(changeVal == '{$value}'){
                {foreach $showFields as $showField}
                $('.form-item-field-{$showField}').removeClass('r-hidden') ;
                {/foreach}
            }
            {/foreach}
        });
        {continue}
        {/if}
        
        {if in_array($cthis->mdl->form[$field]['elem'],array('radio','checker'))}
        {if $cthis->mdl->form[$field]['elem'] == 'radio'}{$event='radio'}{/if}
        {if $cthis->mdl->form[$field]['elem'] == 'checker'}{$event='switch'}{/if}
        form.on('{$event}({$field})', function(data){
            {if $respond.RespondField}
                {foreach $respond.RespondField as $hideField}
                $('.form-item-field-{$hideField}').addClass('r-hidden') ;
                {/foreach}
            {/if}
            var changeVal  =  $(this).closest('.layui-input-inline').find(':checked').val();
            {foreach $respond as $value=>$showFields}
            {if $value == 'RespondField'}{continue}{/if}
            if(changeVal == '{$value}'){
                {foreach $showFields as $showField}
                $('.form-item-field-{$showField}').removeClass('r-hidden') ;
                {/foreach}
            }
            {/foreach}
        });
        {continue}
        {/if}
    {/foreach}
    {/if}
});




var $editors=$('.editor');
if($editors.length){
	var ckeditor_setting={
		baseHref:wwwroot,
		toolbar:'AdminFull',		
        filebrowserImageUploadUrl:"{url('Upload/uploader',['type'=>'image','model'=>$mdl])}",		
        allowedContent:true,
		width:'800px',
		height:'280px',
		dummy:'dummy'
	};
	$editors.ckeditor(ckeditor_setting) ;
}

$('.form_upload').change(function(){
    $(this).closest('div').find('.upload_elem_info').html('新文件：'+$(this).val()).css('display','block') ;
})

$('.upload_remove_btn').click(function(e){
    var that = $(this);
    layer.confirm('请确认是否真的删除？',function(val, index){
        that.closest('div.form_elem_info').find('input').val('') ;
        that.parent().remove();
        layer.closeAll();
    });
    e.stopPropagation();
    return false ;
})



if(typeof(TPL) != 'undefined'){

//{literal}
	TPL.show_array=function(){/*
<table cellspacing="1" cellpadding="0" border="0" style="width:auto">
	{each $value as $p_val $p_index}
	<tr><td align="right" style=" border:0; padding:3px;">{$p_index}.</td><td style="border:0; padding:3px;">=></td><td style="border:0; padding:3px;{if $p_val===''}background:#039; color:#fff;{else}background:#f3f3f3;{/if}" align="left">{if $p_val===''}空{else}{$p_val}{/if}</td></tr>
	{/each}
</table>
*/}
	TPL.show_keyvalue=function(){/*
<table cellspacing="1" cellpadding="0" border="0" style="width:auto">
	{each $value as $p_val $p_key}
	<tr><td align="right" style="border:0; padding:3px;{if $p_key===''}background:#039; color:#fff;{else}background:#f3f3f3;{/if}">{if $p_key===''}空{else}{$p_key}{/if}</td><td  style="border:0; padding:3px;">=></td><td style="border:0; padding:3px;{if $p_val===''}background:#039; color:#fff;{else}background:#f3f3f3;{/if}" align="left">{if $p_val===''}空{else}{$p_val}{/if}</td></tr>
	{/each}
</table>
*/}
	
	TPL.edit_array=function(){/*
<div class="edit_array">
	<div class="copy_template" style="display:none;">
		<div class="array_item">
		<div class="array_item">
		<table class="form_item" border="0" cellpadding="0" cellspacing="0"><tr><td>
		<input type="text" value="" class="layui-input text-input form_item" name="array_value[]">
		</td><td><a class="javascript" rel="array_item_remove" title="删除" ><i class="fa fa-minus-circle"></i> 删除</a> <a class="javascript" rel="array_item_insert" title="插入"><i class="fa fa-plus-circle"></i> 插入</a></td></tr></table>
		</div>
		</div>
	</div>
	<div class="array_items">
		{each $value as $p_val}
		<div class="array_item">
		<table class="form_item" border="0" cellpadding="0" cellspacing="0"><tr><td>
		<input type="text" value="{$p_val}" class="layui-input text-input form_item" name="array_value[]">
		</td><td><a class="javascript" rel="array_item_remove" title="删除" ><i class="fa fa-minus-circle"></i> 删除</a> <a class="javascript" rel="array_item_insert" title="插入"><i class="fa fa-plus-circle"></i> 插入</a></td></tr></table>
		</div>
		{/each}
	</div>
	<a class="javascript add-item" rel="array_item_create" title="添加新项"><i class="fa fa-plus"></i> 添加新项</a>
</div>
*/}
	TPL.edit_keyvalue=function(){/*
<div class="edit_array">
	<div class="copy_template" style="display:none;">
		<div class="array_item">
		<div class="array_item">
		<table class="form_item" border="0" cellpadding="0" cellspacing="0"><tr><td>
		<input type="text" value="" class="layui-input text-input form_item form_key" name="array_value[key][]"></td>
        <td>
		<input type="text" value="" class="layui-input text-input form_item form_value" name="array_value[value][]">
		</td><td><a class="javascript" rel="array_item_remove" title="删除" ><i class="fa fa-minus-circle"></i> 删除</a><a class="javascript  " rel="array_item_insert" title="插入"><i class="fa fa-plus-circle"></i> 插入</a></td></tr></table>
		</div>
		</div>
	</div>
	<div class="array_items">
		{each $value as $p_val $p_key}
		<div class="array_item">
		<table class="form_item" border="0" cellpadding="0" cellspacing="0"><tr><td>
		<input type="text" value="{$p_key}" class="layui-input text-input form_item form_key" name="array_value[key][]"></td>
        <td>
		<input type="text" value="{$p_val}" class="layui-input text-input form_item form_value" name="array_value[value][]">
		</td><td><a class="javascript" rel="array_item_remove" title="删除" ><i class="fa fa-minus-circle"></i> 删除</a><a class="javascript " rel="array_item_insert" title="插入"><i class="fa fa-plus-circle"></i> 插入</a></td></tr></table>
		</div>
		{/each}
	</div>
	<a class="javascript add-item" rel="array_item_create" title="添加新项"><i class="fa fa-plus"></i> 添加新项</a>
</div>
*/}

//{/literal}
}

function show_array(){
	var is_keyvalue=$(this).is('.keyvalue'); 
	var value=get_array_value.call(this);
	
	$(this).removeClass('editing').html('编辑').siblings('.array').html((is_keyvalue?TPL.show_keyvalue:TPL.show_array).render({
		$value:value
	}));
}

function edit_array(){
	var $this=$(this);
    
	var is_keyvalue=$this.is('.keyvalue');
	
	if($this.is('.editing')){
		var value=HKUC.parse_serial_array($this.siblings('.array').find('.array_items input[type=text]').serializeArray());
		
		(is_keyvalue?set_keyvalue_value:set_array_value).call(this,value.array_value);
		show_array.call(this);
	}
	else{
		var value=get_array_value.call(this);
		
		$this.addClass('editing').html('保存').siblings('.array').html((is_keyvalue?TPL.edit_keyvalue:TPL.edit_array).render({
			$value:value
		}));
	}
}

function get_array_value(){
	var raw_value=$(this).siblings('.form_item').val();
	
	if(HKUC.isJsonValidate(raw_value)){
		return eval('('+raw_value+')');
	}
	else{
		return [];
	}
}

function set_array_value(value){
	$(this).siblings('.form_item').val(JSON.stringify(value));
}

function set_keyvalue_value(value){
	var ret={};
	if(value && value.key)
	for(key in value.key){
		ret[value.key[key]]=value.value[key];
	}	
	$(this).siblings('.form_item').val(JSON.stringify(ret));
}

function array_item_create($obj){
	var $this=$(this);
	var new_item_str=$this.closest('.array').find('.copy_template').html();

	if($obj){
		$(new_item_str).find(':disabled').attr('disabled',false).end().insertBefore($obj);
	}
	else{
		$(new_item_str).find(':disabled').attr('disabled',false).end().appendTo($this.siblings('.array_items'));
	}
}

function array_item_insert(){
	array_item_create.call(this,$(this).closest('.array_item'));
}

function array_item_remove(){
	var $this=$(this);
	var $item=$this.closest('.array_item');

	$item.remove();
}

var textWidth = function (text) {
    var sensor = $('<div>' + text + '</div>').css({
        display: 'none'});
    $('body').append(sensor);
    var width = sensor.width();
    sensor.remove();
    return width;
};

$('.tag_write').keyup(function(){
    var tw = textWidth($(this).val());
    var width = tw > 60 ? tw : 60;
    $(this).width(width);    
}).keydown(function(e){
    if (e.keyCode == 13) {
        insert_tag(this);       
        e.stopPropagation();
        return false;
    }
}).blur(function(){
    insert_tag(this); 
})

function insert_tag(obj) {
    var value = $.trim($(obj).val());
    if (!value) return false;
    var isExist = false;
    var valArray = [];
    var length = parseInt($(obj).closest('.form_tag_container').data('length'));
    var i = 0;
    $(obj).closest('.form_tag_container').find('a.tag_each').each(function(){
        i++;
        var tag = $(this).data('value');
        if (value == tag) {
            isExist = true;
            return false;
        }        
        if (i >= length && length) {
            isExist = true;
            return false;
        }        
        valArray.push(tag);
    })    
    if (!isExist) {
        valArray.push(value);
        var html = $('<a class="tag_each" data-value="'+value+'">'+value+'<i class="fa fa-close"></i></a>')
        html.insertBefore($(obj));
        $(obj).closest('.form_tag_container').find('.form_item').val(valArray.join(','));
    }
    $(obj).val('').trigger('keyup');
}

$('body').on('click', '.form_tag_container .tag_each i',function(){
    var parent = $(this).closest('.form_tag_container');
    $(this).parent().remove();
    var valArray = [];
    parent.find('a.tag_each').each(function(){
        var tag = $(this).data('value');
        valArray.push(tag);
    })
    parent.find('.form_item').val(valArray.join(','));
})

$('body').on('dblclick', '.form_tag_container .tag_each',function(){
    var parent = $(this).closest('.form_tag_container');
    $(this).remove();
    var valArray = [];
    parent.find('a.tag_each').each(function(){
        var tag = $(this).data('value');
        valArray.push(tag);
    })
    parent.find('.form_item').val(valArray.join(','));
})

$('body').on('click', '.form_tag_container', function(){
    $(this).find('input[type="text"]').focus();
})



//表单分组
if($('.form_selector').length){
    var mt  = -($('.form_selector').height() / 2) ;
    $('.form_selector').css({
        'margin-top' : mt
    })
    
    $('.form_selector').find('li').click(function(){
        var index  = $(this).index();
        var show_class = 'form-item-group-' + $(this).attr('data-group-key') ;
        $('.box_form').find('.box_content').find('.form-item-row').not('.'+show_class).addClass('hidden');
        $('.box_form').find('.box_content').find('.form-item-row.'+show_class).removeClass('hidden')
        $('.form_selector').find('li.current').removeClass('current').end().find('li:eq('+index+')').addClass('current') ;
    })
    //表单分组快捷切换方式 ：alt+Q
    document.onkeydown = function(event){
        if (event.keyCode == 81 && event.altKey){
            var max_index  =  $('.form_selector').find('li').length -1 ;
            var index    = $('.form_selector').find('li.current').index() + 1;
            if(index > max_index) index =  0 ;
            $('.form_selector').find('li:eq('+index+')').trigger('click') ;
        }
    }
}

//导航选取

$('.menu_select_show,.menu_select_action').click(function(){
    $(this).parent().css('z-index', 10).find('.menu_select_options').stop().show()
})

$('.menu_select').hover(jQuery.noop,function(){
    $(this).css('z-index', 9).find('.menu_select_options').stop().hide()
})

$('.menu_select_options').find('a.each_nav').click(function(){
    var parent_index = $(this).parent().index();
    var index  = $(this).index();
    var id           = $(this).attr('data-id');    
    $(this).parent().parent().find('.menu_option:gt('+parent_index+')').hide().find('a.same').removeClass('same').end().end().find('.menu_option_parent_'+id).show();
    $(this).parent().find('a.same').removeClass('same').end().find('a:eq('+index+')').addClass('same');
    var family_str = [];
    $(this).closest('.menu_select_options').find('a.same').each(function(){
        family_str.push($(this).text());
    })    
    $(this).parent().parent().parent().find('.menu_select_show').html(family_str.join('<i>&gt;</i>')).end().find('.form_item').val(id)
})

$('.icon_select_action').click(function(){
    if ($(this).closest('.icon_select').find('.icon_select_options').is(':visible')) {
        $(this).closest('.icon_select').find('.icon_select_options').hide();
        $(this).html('搜索图标');
        return false;
    }
    $(this).html('关闭图标');
    var len =  $(this).closest('.icon_select').find('.icon_select_options').show().find('li').length;
    if (len <= 0) {
        var that = $(this);
        HKUC.ajax_request.call(this, "{url('run/Tool/get_awesome')}", null,
    	{
    		'success':function(msg,data){
                var html = '<div class="icon_search"><input placeholder="输入关键词搜索" class="layui-input icon_search_input"></div><ul class="grid">';
                for (i in data) {
                    html += '<li><i class="fa '+ data[i] +'" aria-hidden="true"></i></li>';
                }
                html += '</ul>';
                that.closest('.icon_select').find('.icon_select_options').html(html);
    		}
    	});
    }
})

$('body').on('keyup', '.icon_search_input', function(){
    var keyword  = $.trim($(this).val());
    if (!keyword) {
        $(this).closest('.icon_select_options').find('li').show();
    } else {
        $(this).closest('.icon_select_options').find('li').each(function(){
            var className = $(this).find('i').attr('class');
            if (className.indexOf(keyword) >=0) {
                $(this).show()
            } else {
                $(this).hide()
            }
        })
    }
})

$('body').on('click', '.icon_select ul li', function(){
    var className = $(this).find('i').attr('class');
    $(this).closest('.icon_select').find('input.form_item').val(className);
    $(this).closest('.icon_select').find('.icon_select_options').hide();
})

$(document).ready(function(){
	$('.edit_array').each(function(){
		show_array.call(this)
	})
    
    $('.layui-input-error').click(function(){
        var animate = ['zoomOutRight','fadeOutRight','flipOutX','flipOutY','rotateOutDownRight','rollOut'];
        var rand    = Math.round(Math.random()*5)
        $(this).addClass(animate[rand]).delay(600).fadeOut(200);
    })
    
    $('.box_form .layui-input-error').fadeIn(200)
});
</script>
{$smarty.block.child}
{/block}
